#import "DBLogsSaveTool.h"

@implementation DBLogsSaveTool

+(NSString *)logFileName:(DLLogsSaveType)logSaveType{
    /// 文件夹名称
    NSString *logsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Library/Caches/log_%lu", (unsigned long)logSaveType]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    /// 文件名称
    NSString *logFile = [NSString stringWithFormat:@"%@/%@", logsDirectory, [dateFormatter stringFromDate:[NSDate date]]];
    NSFileManager *mrg = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [mrg fileExistsAtPath:logsDirectory isDirectory:&isDir];
    
    /// 创建文件夹
    if (!(isDir == YES && existed == YES)) {
        [mrg createDirectoryAtPath:logsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    /// 判断有没有文件，如果有文件，那就跳过
    if (![mrg fileExistsAtPath:logFile]) {
        /// 如果没有，说明之前的文件是老文件，那么全部删除
//        for (NSString *oldFile in [mrg contentsOfDirectoryAtPath:logsDirectory error:nil]) {
//            [mrg removeItemAtPath:[NSString stringWithFormat:@"%@/%@", logsDirectory, oldFile] error:nil];
//        }
        /// 创建新的文件
        [mrg createFileAtPath:logFile contents:nil attributes:nil];
    }
    NSLog(@"%@", logFile);
    return logFile;
}

+(NSString *)logsDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM:dd HH:mm:ss-SSS"];
    return [dateFormatter stringFromDate:[NSDate date]];
}


+(void)writeLogs:(NSString *)str funcLog:(NSString *)funcStr logSaveType:(DLLogsSaveType)logSaveType {
    NSString *logs = [NSString stringWithFormat:@"%@  %@  %@\n", [DBLogsSaveTool logsDate], funcStr, str];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:[DBLogsSaveTool logFileName:logSaveType]];
        [fileHandle seekToEndOfFile]; //将节点跳到文件的末尾
        NSData *stringData = [logs dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle writeData:stringData]; // 追加写入数据
        [fileHandle closeFile];
    });
}

+(void)writeLogs:(NSString *)str logSaveType:(DLLogsSaveType)logSaveType {
    NSString *logsDate = [DBLogsSaveTool logsDate];
    NSLog(@"%@", logsDate);
    NSString *logs = [NSString stringWithFormat:@"%@  %@\n", logsDate, str];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:[DBLogsSaveTool logFileName:logSaveType]];
        [fileHandle seekToEndOfFile]; //将节点跳到文件的末尾
        NSData *stringData = [logs dataUsingEncoding:NSUTF8StringEncoding];
        [fileHandle writeData:stringData]; // 追加写入数据
        [fileHandle closeFile];
    });
}

@end
